﻿using Scap.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Scap.Info;
using System.Data;
using PagedList;
using Scap.Web.Models;
using Scap.Web.CommonCode;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.UI;

namespace Scap.Web.Controllers
{
    public class tabsEmpleadoController : Controller
    {
        private ScapData db = new ScapData();

        int _pageIndex = 0;
        public int PageIndex
        {
            get { return _pageIndex; }
            set { _pageIndex = value; }
        }

        int _pageSize = 15;
        //int _pageSize = 2;
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }

        //
        // GET: /tabsEmpleado/BuscarDepartamento
        [NoCache]
        public PartialViewResult MostrarDepartamentos(string departamentId, string tipodepartamento, int? page)
        {
            int nDepartamentoId = 0;
            int nTipoDepartamento = 0;
            string szName = "";
            string szDescripcion = "";

            IQueryable<ScapDepartment> qryDpto = null;
            IQueryable<ScapDepartmentType> qrytipoDpto = null;
            ScapDepartment departamento = null;
            ScapDepartmentType tipodpto = null;

            //if (string.IsNullOrEmpty(departamentId))
            //{
            //    nDepartamentoId = 0;
            //}
            //else
            //{
            //    nDepartamentoId = Convert.ToInt32(departamentId);
            //}

            //Get tipo departamento
            if (string.IsNullOrEmpty(tipodepartamento))
            {
                tipodepartamento = "Departamento";
            }
            qrytipoDpto = db.DepartmentTypes.Where(tpdp => tpdp.Name == tipodepartamento);
            tipodpto = qrytipoDpto.FirstOrDefault<ScapDepartmentType>();
            if (tipodpto != null)
            {
                nTipoDepartamento = tipodpto.Id;
            }

            //Get Departamento Data
            qryDpto = db.Departments.Where(dpt => dpt.Name == departamentId && dpt.TypeId == nTipoDepartamento);
            departamento = qryDpto.FirstOrDefault<ScapDepartment>();
            if (departamento != null)
            {
                szName = departamento.Name;
                szDescripcion = departamento.Description;
            }
            ViewBag.DepartamentoName = szName;
            ViewBag.DepartamentoDescripcion = szDescripcion;
            ViewBag.TipoDepartamento = tipodepartamento;

            return PartialView();
        }

        //
        //Obtiene la informacion para mostrar el treeview, utilizando JSON, todo el tree
        [NoCache]
        public JsonResult getJsonData01(string tipodepartamento)
        {
            int nPos = -1;
            int nParentId = 0;
            int nTipoDepartamento = 0;
            string szDepartamento = "";
            string szMsg = "";
            string szDescripcion = "";
            string szPath = "";

            IQueryable<ScapDepartmentType> qryTpdt = null;
            IQueryable<ScapDepartment> qryDpto = null;
            ScapDepartmentType tipoDepto = null;
            ScapDepartment depto = null;

            List<string> itemsList = new List<string>();
            List<TreeViewData> modelList = null;

            //Obtiene le tipo de departamento
            qryTpdt = db.DepartmentTypes.Where(tpdp => tpdp.Name == tipodepartamento);
            tipoDepto = qryTpdt.FirstOrDefault<ScapDepartmentType>();
            if (tipoDepto != null)
            {
                nTipoDepartamento = tipoDepto.Id;
            }

            //Obtiene los departamentos sin padres
            qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTipoDepartamento && dpto.ParentDepartmentId == null).OrderBy(dpto => dpto.Description);
            if (qryDpto.Count() > 0)
            {
                modelList = new List<TreeViewData>();

                foreach (var item in qryDpto)
                {
                    TreeViewData model = new TreeViewData();
                    model.id = string.Format("\\/{0}", item.Name);
                    model.item = string.Format("{0}", item.Description);

                    TreeViewProps props = new TreeViewProps();
                    props.icon = "folder";
                    props.isFolder = "false";
                    props.open = "true";
                    model.props = props;

                    model.parentpath = string.Format("/{0}", item.Name);

                    //Get the childs of this branch
                    //Obtiene descendientes
                    List<TreeViewData> childs = GetChilds01(item.Id, item.Name, model.parentpath);
                    if (childs == null)
                    {
                        model.items = null;
                    }
                    else
                    {
                        model.items = childs;
                    }

                    modelList.Add(model);

                }
            }

            return Json(modelList);
        }

        //Obtiene la informacion para mostrar el treeview, utilizando JSON
        [NoCache]
        public JsonResult getJsonData(string departamento, string parentpath, string tipodepartamento)
        {
            int nPos = -1;
            int nParentId = 0;
            string szDepartamento = "";
            string szMsg = "";
            string szDescripcion = "";
            string szPath = "";
            string szTipoDepartamento = "";

            IQueryable<ScapDepartment> qryDpto = null;
            ScapDepartment depto = null;
            ScapDepartmentType tipdepto = null;

            //szPath = string.Format("/{0}", departamento);

            szDepartamento = departamento;
            szDepartamento = szDepartamento.Replace("\\", "");
            szDepartamento = szDepartamento.Replace("/", "");
            qryDpto = db.Departments.Where(dpt => dpt.Name == szDepartamento);
            depto = qryDpto.FirstOrDefault<ScapDepartment>();
            if (depto != null)
            {
                szDescripcion = depto.Description;
                nParentId = depto.Id;
                ViewBag.DepartamentoName = depto.Name;
                ViewBag.DepartamentoDescripcion = depto.Description;
                ViewBag.TipoDepartamento = depto.TypeId;
            }

            if (depto.TypeId != 0)
            {
                tipdepto = db.DepartmentTypes.Find(depto.TypeId);
                if (tipdepto != null)
                {
                    szTipoDepartamento = tipdepto.Name;
                }
            }

            List<string> itemsList = new List<string>();

            // ScapCompany company = db.Companies.FirstOrDefault<ScapCompany>();
            List<TreeViewData> modelList = null;

            if (string.IsNullOrEmpty(parentpath))
            {
                modelList = new List<TreeViewData>();

                TreeViewData model = new TreeViewData();
                model.id = string.Format("\\/{0}", departamento);
                model.item = string.Format("{0}", szDescripcion);
                model.tipodepartamento = szTipoDepartamento;

                TreeViewProps props = new TreeViewProps();
                props.icon = "folder";
                props.isFolder = "false";
                props.open = "true";
                model.props = props;

                model.parentpath = string.Format("/{0}", departamento);

                //Get the childs of this branch
                //Obtiene descendientes
                List<TreeViewData> childs = GetChilds01(nParentId, szDepartamento, model.parentpath);
                if (childs == null)
                {
                    model.items = null;
                }
                else
                {
                    model.items = childs;
                }

                modelList.Add(model);

            }
            else
            {
                modelList = new List<TreeViewData>();

                qryDpto = db.Departments.Where(dpt => dpt.ParentDepartmentId == nParentId).OrderBy(dpt => dpt.Name);
                if (qryDpto != null)
                {
                    foreach (var item in qryDpto)
                    {
                        TreeViewData model = new TreeViewData();
                        model = new TreeViewData();
                        model.id = string.Format("{0}", item.Name);
                        model.item = string.Format("{0}", item.Description);

                        TreeViewProps props = new TreeViewProps();
                        props.icon = "folder";
                        props.isFolder = "false";
                        props.open = "true";
                        model.props = props;
                        model.items = null;

                        //Set the parent path
                        nPos = parentpath.IndexOf("has not been found!");
                        if (nPos != -1)
                        {
                            szMsg = departamento;
                            szMsg = szMsg.Replace("\\", "");

                            nPos = -1;
                            nPos = parentpath.IndexOf(":[");
                            if (nPos != -1)
                            {
                                szMsg = parentpath.Substring(nPos + 2);
                                nPos = -1;
                                nPos = szMsg.IndexOf("]:");
                                if (nPos != -1)
                                {
                                    szMsg = szMsg.Substring(0, nPos);
                                }
                            }
                            model.parentpath = szMsg;
                        }

                        //The path is:
                        nPos = -1;
                        nPos = parentpath.IndexOf("The path is:");
                        if (nPos != -1)
                        {
                            szMsg = departamento;
                            szMsg = szMsg.Replace("\\", "");

                            nPos = -1;
                            nPos = parentpath.IndexOf(":[");
                            if (nPos != -1)
                            {
                                szMsg = parentpath.Substring(nPos + 2);
                                nPos = -1;
                                nPos = szMsg.IndexOf("]:");
                                if (nPos != -1)
                                {
                                    szMsg = szMsg.Substring(0, nPos);
                                }
                            }
                            model.parentpath = szMsg;
                        }

                        modelList.Add(model);

                    }
                }


                //TreeViewData model = new TreeViewData();
                //if (departamento == "Item A")
                //{
                //    model.id = "Item B";
                //    model.item = "Item B - ChiltData";
                //}
                //else
                //{
                //    model.id = "Item A";
                //    model.item = "Item A - ChiltData";
                //}
                //TreeViewProps props = new TreeViewProps();
                //props.icon = "folder";
                //props.isFolder = "false";
                //props.open = "false";
                //model.props = props;
                //model.items = itemsList;

                ////Set the parent path
                //nPos = parentpath.IndexOf("has not been found!");
                //if (nPos != -1)
                //{
                //    szMsg = departamento;
                //    szMsg = szMsg.Replace("\\", "");

                //    nPos = -1;
                //    nPos = parentpath.IndexOf(":[");
                //    if (nPos != -1)
                //    {
                //        szMsg = parentpath.Substring(nPos + 2);
                //        nPos = -1;
                //        nPos = szMsg.IndexOf("]:");
                //        if (nPos != -1)
                //        {
                //            szMsg = szMsg.Substring(0, nPos);
                //        }
                //    }
                //    model.parentpath = szMsg;
                //}

                //modelList.Add(model);


            }


            return Json(modelList);
        }

        private List<TreeViewData> GetChilds01(int nParentId, string szDepartamento, string szPath)
        {
            List<TreeViewData> descendientes = null;

            bool bStatus = false;
            int nHas = -1;
            int nItemId = 0;
            string szName = "";
            string szError = "";
            string szSql = "";
            string szConnString = "";
            SqlDataSource sqlds = new SqlDataSource();
            DataView dv = null;
            ConnectionStringSettingsCollection connSettings = ConfigurationManager.ConnectionStrings;

            try
            {

                //szConnString = connSettings["ApplicationServices"].ToString();
                szConnString = connSettings["SCAPDB"].ToString();
                sqlds.ConnectionString = szConnString;

                szSql = string.Format("SELECT Id, Name, Description, ParentDepartmentId  FROM ScapDepartment WHERE ( ParentDepartmentId = {0}) " +
                    "ORDER BY Name", nParentId);
                sqlds.SelectCommand = szSql;
                dv = (DataView)sqlds.Select(DataSourceSelectArguments.Empty);
                nHas = dv.Count;
                if (nHas > 0)
                {
                    descendientes = new List<TreeViewData>();

                    for (int i = 0; i < nHas; i++)
                    {
                        TreeViewData model = new TreeViewData();
                        model.id = string.Format("{0}", dv[i]["Name"].ToString());
                        model.item = string.Format("{0}", dv[i]["Description"].ToString());

                        TreeViewProps props = new TreeViewProps();
                        props.icon = "folder";
                        props.isFolder = "false";
                        props.open = "true";
                        model.props = props;

                        model.parentpath = string.Format("{0}", szPath);

                        //model.parentpath = string.Format("{0}/{1}", szPath, szDepartamento);
                        //model.parentpath = string.Format("{0}/{1}", model.parentpath, szDepartamento);

                        //model.items = null;

                        //Get the childs of this branch
                        //Obtiene descendientes
                        nItemId = Convert.ToInt32(dv[i]["Id"]);
                        szName = dv[i]["Name"].ToString();
                        List<TreeViewData> childs = GetChilds01(nItemId, szName, string.Format("{0}/{1}", model.parentpath, szName));
                        if (childs == null)
                        {
                            model.items = null;
                        }
                        else
                        {
                            model.items = childs;
                        }

                        descendientes.Add(model);

                    }
                    //szNoProperties = dv[0]["Name"].ToString();
                    bStatus = true;
                }
            }
            catch (Exception exc)
            {
                szError = exc.Message;
            }


            return descendientes;
        }

        private List<TreeViewData> GetChilds(int nParentId, string szDepartamento, string szPath)
        {
            //string szDepartamentoDescendiente = "";
            //string szDescripcion = "";

            List<TreeViewData> descendientes = null;
            //ScapDepartment departamento = null;

            IQueryable<ScapDepartment> qryDpto = null;

            qryDpto = db.Departments.Where(dpt => dpt.ParentDepartmentId == nParentId).OrderBy(dpt => dpt.Name);
            if (qryDpto != null)
            {
                descendientes = new List<TreeViewData>();

                foreach (var item in qryDpto)
                {
                    TreeViewData model = new TreeViewData();
                    model.id = string.Format("{0}", item.Name);
                    model.item = string.Format("{0}", item.Description);

                    TreeViewProps props = new TreeViewProps();
                    props.icon = "folder";
                    props.isFolder = "false";
                    props.open = "true";
                    model.props = props;

                    model.parentpath = string.Format("{0}", szPath);

                    //model.parentpath = string.Format("{0}/{1}", szPath, szDepartamento);
                    //model.parentpath = string.Format("{0}/{1}", model.parentpath, szDepartamento);

                    //model.items = null;

                    //Get the childs of this branch
                    //Obtiene descendientes
                    List<TreeViewData> childs = GetChilds(item.Id, item.Name, string.Format("{0}/{1}", model.parentpath, item.Name));
                    if (childs == null)
                    {
                        model.items = null;
                    }
                    else
                    {
                        model.items = childs;
                    }

                    descendientes.Add(model);
                }
            }
            return descendientes;
        }


        //private void GetChilds(int nParentId, string departamento, string szDescripcion, ref List<TreeViewData> modelList)
        //{
        //    TreeViewData model = null;
        //    List<string> itemsList = new List<string>();

        //    IQueryable<ScapDepartment> qryDpto = null;
        //    ScapDepartment depto = null;

        //    qryDpto = db.Departments.Where(dpt => dpt.ParentDepartmentId == nParentId).OrderBy(dpt => dpt.Name);
        //    if (qryDpto != null)
        //    {
        //        foreach (var item in qryDpto)
        //        {
        //            model = new TreeViewData();
        //            model.id = string.Format("{0}", item.Name);
        //            model.item = string.Format("{0}", item.Description);

        //            TreeViewProps props = new TreeViewProps();
        //            props.icon = "folder";
        //            props.isFolder = "false";
        //            props.open = "true";
        //            model.props = props;
        //            model.items = itemsList;
        //            modelList.Add(model);

        //        }
        //    }
        //}


        //
        // GET: /tabsEmpleado/BuscarDepartamento
        [NoCache]
        public PartialViewResult BuscarDepartamento(string departamentId, string tipodepartamento, int? page)
        {
            bool bHasPreviousPage = false;
            bool bHasNextPage = false;
            int nPageCount = 1;
            int nPageNumber = 0;
            int pageIndex = 0;
            int pageSize = PageSize;
            int nDepartamentoId = 0;
            int nTipoDepartamento = 0;
            int nDepartamentoRegresa = 0;
            string szDeptoPadre = "";
            string szDeptoPadreNombre = "";

            ScapDepartment departamento = null;
            ScapDepartment departamentoregresa = null;
            IQueryable<ScapDepartment> qryDpto = null;
            List<ScapDepartment> departamentoList = new List<ScapDepartment>();

            //if (string.IsNullOrEmpty(departamentId))
            //{
            //    nDepartamentoId = 0;
            //}
            //else
            //{
            //    nDepartamentoId = Convert.ToInt32(departamentId);
            //}


            //departamento = db.Departments.Find(nDepartamentoId);
            qryDpto = db.Departments.Where(dpt => dpt.Name == departamentId);
            departamento = qryDpto.FirstOrDefault<ScapDepartment>();
            if (departamento != null)
            {
                szDeptoPadre = departamento.Description;
                szDeptoPadreNombre = departamento.Name;
                nDepartamentoId = departamento.Id;
                if (departamento.ParentDepartmentId != null)
                {
                    nDepartamentoRegresa = Convert.ToInt32(departamento.ParentDepartmentId);
                    departamentoregresa = db.Departments.Find(nDepartamentoRegresa);
                    if (departamentoregresa != null)
                    {
                        ViewBag.DepartamentoRegresa = departamentoregresa.Name;
                    }
                }
            }
            ViewBag.DepartamentoPadreId = nDepartamentoId;
            ViewBag.DepartamentoPadre = szDeptoPadre;
            ViewBag.DepartamentoPadreNombre = szDeptoPadreNombre;


            if (nDepartamentoId != 0)
            {
                qryDpto = db.Departments.Where(dpto => dpto.ParentDepartmentId == nDepartamentoId);
                if (qryDpto.Count() > 0)
                {
                    foreach (var item in qryDpto)
                    {
                        departamentoList.Add(item);
                    }
                }
            }

            if (string.IsNullOrEmpty(tipodepartamento))
            {
                tipodepartamento = "Departamento";
            }

            ViewBag.TipoDepartamento = tipodepartamento;

            //Set the page
            if (page == null)
            {
                pageIndex = 1;
            }
            else
            {
                pageIndex = Convert.ToInt32(page);
            }
            nPageNumber = pageIndex;
            ViewBag.PageCount = nPageCount;
            ViewBag.PageNumber = nPageNumber;
            ViewBag.HasPreviousPage = bHasPreviousPage;
            ViewBag.HasNextPage = bHasNextPage;

            //return PartialView(departamentoList.ToPagedList(pageIndex, pageSize));
            return PartialView(departamentoList);
        }

        //
        // GET: /tabsEmpleado/AddEmployee
        [NoCache]
        public ActionResult AddEmployee(int id = 0)
        {
            int nTipoDepartamento = 0;
            int nRole = 0;
            int nParentId = 0;
            string szParentName = "";
            string szTipoDepartamento = "";
            string szStartDate = "";
            DateTime dNacimiento = DateTime.Now;

            List<KeyValuePair<string, string>> optionList = null;
            SelectList selectHlp = null;

            IQueryable<ScapEmployeeType> qryEmpType = null;
            ScapEmployeeType employeetipo = null;

            IQueryable<ScapEmployeeStatus> qryEmpSts = null;
            ScapEmployeeStatus employeestatus = null;

            IQueryable<ScapDepartment> qryDpto = null;
            ScapDepartment departamento = null;
            IQueryable<ScapDepartmentType> qryTpDpto = null;

            ScapDepartmentType tipoDepto = null;
            IQueryable<ScapLocationCity> qryCid = null;

            ScapEmployee employee = null;

            IQueryable<ScapEmployeeRole> qryRol = null;
            ScapEmployeeRole roles = null;

            IQueryable<ScapDepartmentEmployee> qryDptoEmpl = null;
            ScapDepartmentEmployee departamentoempleado = null;

            if (id == 0)
            {
                //Crea un nuevo empleado
                employee = new ScapEmployee();
                employee.Birthday = dNacimiento;

                ViewBag.Title = "Añadir Empleado";
                ViewBag.OriginCityId = new SelectList(db.LocationCities, "Id", "Name", employee.OriginCityId);
                ViewBag.ResidenceCityId = new SelectList(db.LocationCities, "Id", "Name", employee.ResidenceCityId);
            }
            else
            {
                employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }

                //Get the default role
                qryRol = db.EmployeeRoles.Where(rl => rl.Name == "Basico");
                roles = qryRol.FirstOrDefault<ScapEmployeeRole>();
                if (roles != null)
                {
                    nRole = roles.Id;
                }

                //Get the departamentemployee data
                qryDptoEmpl = db.DepartmentEmployees.Where(dpem => dpem.RoleId == nRole && dpem.EmployeeId == employee.Id);
                departamentoempleado = qryDptoEmpl.FirstOrDefault<ScapDepartmentEmployee>();
                if (departamentoempleado != null)
                {
                    //Get the display values
                    departamento = db.Departments.Find(departamentoempleado.DepartmentId);
                    if (departamento != null)
                    {
                        //Verifica si es un elemento sin padre (inicial)
                        departamento = db.Departments.Find(departamentoempleado.DepartmentId);
                        if (departamento != null)
                        {
                            if (departamento.ParentDepartmentId == null)
                            {
                                ViewBag.DepartamentoEmpleadoDepto = departamentoempleado.Deparment.Name;
                            }
                            else
                            {
                                //Get parent data
                                GetParentData(departamentoempleado.Deparment.Name, ref szParentName, ref nParentId, departamento.TypeId);
                                ViewBag.DepartamentoEmpleadoDepto = szParentName;
                                ViewBag.DepartamentoEmpleadoDepto01 = departamentoempleado.Deparment.Name;
                            }
                        }
                    }

                    if (departamentoempleado != null)
                    {
                        employeetipo = db.EmployeeTypes.Find(departamentoempleado.EmployeeTypeId);
                        if (employeetipo != null)
                        {
                            ViewBag.TipoEmpleado = employeetipo.Id;
                        }

                        employeestatus = db.EmployeeStatus.Find(departamentoempleado.EmploymentStatusId);
                        if (employeestatus != null)
                        {
                            ViewBag.EstadoEmpleado = employeestatus.Id;
                        }

                        szStartDate = departamentoempleado.StartDate.ToString("dd/MM/yyyy");
                        ViewBag.StartDate = szStartDate;

                    }


                    //Get the default role
                    qryRol = db.EmployeeRoles.Where(rl => rl.Name == "BasicoArea");
                    roles = qryRol.FirstOrDefault<ScapEmployeeRole>();
                    if (roles != null)
                    {
                        nRole = roles.Id;
                    }

                    //Get the departamentemployee data
                    qryDptoEmpl = db.DepartmentEmployees.Where(dpem => dpem.RoleId == nRole && dpem.EmployeeId == employee.Id);
                    departamentoempleado = qryDptoEmpl.FirstOrDefault<ScapDepartmentEmployee>();
                    if (departamentoempleado != null)
                    {
                        //Get the display values
                        departamento = db.Departments.Find(departamentoempleado.DepartmentId);
                        if (departamento != null)
                        {
                            //Verifica si es un elemento sin padre (inicial)
                            departamento = db.Departments.Find(departamentoempleado.DepartmentId);
                            if (departamento != null)
                            {
                                if (departamento.ParentDepartmentId == null)
                                {
                                    ViewBag.DepartamentoEmpleadoArea = departamentoempleado.Deparment.Name;
                                }
                                else
                                {
                                    //Get parent data
                                    GetParentData(departamentoempleado.Deparment.Name, ref szParentName, ref nParentId, departamento.TypeId);
                                    ViewBag.DepartamentoEmpleadoArea = szParentName;
                                    ViewBag.DepartamentoEmpleadoArea01 = departamentoempleado.Deparment.Name;
                                }
                            }
                        }
                    }

                    if (departamentoempleado != null)
                    {
                        employeetipo = db.EmployeeTypes.Find(departamentoempleado.EmployeeTypeId);
                        if (employeetipo != null)
                        {
                            ViewBag.TipoEmpleado = employeetipo.Id;
                        }

                        employeestatus = db.EmployeeStatus.Find(departamentoempleado.EmploymentStatusId);
                        if (employeestatus != null)
                        {
                            ViewBag.EstadoEmpleado = employeestatus.Id;
                        }

                        szStartDate = departamentoempleado.StartDate.ToString("dd/MM/yyyy");
                        ViewBag.StartDate = szStartDate;

                    }
                }

                ViewBag.Title = "Editar Empleado";
                ViewBag.OriginCityId = new SelectList(db.LocationCities, "Id", "Name", employee.OriginCityId);
                ViewBag.ResidenceCityId = new SelectList(db.LocationCities, "Id", "Name", employee.ResidenceCityId);
            }


            //Define selectores
            optionList = new List<KeyValuePair<string, string>>();
            optionList.Add(new KeyValuePair<string, string>("Masculino", "Masculino"));
            optionList.Add(new KeyValuePair<string, string>("Femenino", "Femenino"));
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.GeneroList = selectHlp;

            optionList = new List<KeyValuePair<string, string>>();
            qryEmpType = db.EmployeeTypes.OrderBy(etp => etp.Name);
            if (qryEmpType.Count() > 0)
            {
                foreach (var itemEtp in qryEmpType)
                {
                    optionList.Add(new KeyValuePair<string, string>(itemEtp.Id.ToString(), itemEtp.Name));
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.EmployeeTypeList = selectHlp;

            optionList = new List<KeyValuePair<string, string>>();
            qryEmpSts = db.EmployeeStatus.OrderBy(empsts => empsts.Name);
            if (qryEmpSts.Count() > 0)
            {
                foreach (var itemEtpSts in qryEmpSts)
                {
                    optionList.Add(new KeyValuePair<string, string>(itemEtpSts.Id.ToString(), itemEtpSts.Name));
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.EmployeeStatusList = selectHlp;

            szTipoDepartamento = "Departamento";
            qryTpDpto = db.DepartmentTypes.Where(tpdpto => tpdpto.Name == szTipoDepartamento);
            tipoDepto = qryTpDpto.FirstOrDefault<ScapDepartmentType>();
            if (tipoDepto != null)
            {
                nTipoDepartamento = tipoDepto.Id;
            }

            optionList = new List<KeyValuePair<string, string>>();
            qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTipoDepartamento).OrderBy(dpto => dpto.Description);
            if (qryDpto.Count() > 0)
            {
                foreach (var itemDpto in qryDpto)
                {
                    if (itemDpto.ParentDepartmentId == null)
                    {
                        //optionList.Add(new KeyValuePair<string, string>(itemDpto.Id.ToString(), itemDpto.Description));
                        optionList.Add(new KeyValuePair<string, string>(itemDpto.Name, itemDpto.Description));
                    }
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.DepartamentoList = selectHlp;

            szTipoDepartamento = "Area";
            qryTpDpto = db.DepartmentTypes.Where(tpdpto => tpdpto.Name == szTipoDepartamento);
            tipoDepto = qryTpDpto.FirstOrDefault<ScapDepartmentType>();
            if (tipoDepto != null)
            {
                nTipoDepartamento = tipoDepto.Id;
            }

            optionList = new List<KeyValuePair<string, string>>();
            qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTipoDepartamento).OrderBy(dpto => dpto.Description);
            if (qryDpto.Count() > 0)
            {
                foreach (var itemDpto in qryDpto)
                {
                    if (itemDpto.ParentDepartmentId == null)
                    {
                        //optionList.Add(new KeyValuePair<string, string>(itemDpto.Id.ToString(), itemDpto.Description));
                        optionList.Add(new KeyValuePair<string, string>(itemDpto.Name, itemDpto.Description));
                    }
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.AreaList = selectHlp;


            optionList = new List<KeyValuePair<string, string>>();
            optionList.Add(new KeyValuePair<string, string>("Si", "Si"));
            optionList.Add(new KeyValuePair<string, string>("No", "No"));
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.WhetherAttendanceList = selectHlp;

            optionList = new List<KeyValuePair<string, string>>();
            optionList.Add(new KeyValuePair<string, string>("Empleado Normal", "Empleado Normal"));
            optionList.Add(new KeyValuePair<string, string>("Registrar", "Registrar"));
            optionList.Add(new KeyValuePair<string, string>("Administrador Sistema", "Administrador Sistema"));
            optionList.Add(new KeyValuePair<string, string>("Super Administrador", "Super Administrador"));
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.AdministratorList = selectHlp;

            optionList = new List<KeyValuePair<string, string>>();
            qryCid = db.LocationCities.OrderBy(dpto => dpto.Name);
            if (qryCid.Count() > 0)
            {
                foreach (var itemDpto in qryCid)
                {
                    optionList.Add(new KeyValuePair<string, string>(itemDpto.Id.ToString(), itemDpto.Name));
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.CiudadList = selectHlp;


            //Get the calendar image path
            string szCalendarPath = Url.Content("~/Images/Calendar.gif");
            ViewBag.CalendarPath = szCalendarPath;


            return View(employee);
        }

        public void GetParentData(string szItemName, ref string szParentName, ref int nParentId, int nTipoDepartamento)
        {
            bool bStatus = false;
            int nParentIdHlp = 0;

            nParentId = 0;
            szParentName = string.Empty;

            IQueryable<ScapDepartment> qryDpto = null;
            ScapDepartment departamento = null;

            //Get the item
            qryDpto = db.Departments.Where(dpt => dpt.TypeId == nTipoDepartamento && dpt.Name == szItemName);
            departamento = qryDpto.FirstOrDefault<ScapDepartment>();
            if (departamento != null)
            {
                //Is this a parent
                if (departamento.ParentDepartmentId == null)
                {
                    return;
                }
                else
                {
                    while (!bStatus)
                    {
                        nParentIdHlp = Convert.ToInt32(departamento.ParentDepartmentId);
                        bStatus = GetParentData01(nParentIdHlp, departamento.TypeId, ref szParentName, ref nParentId);

                    }
                }
            }
        }

        private bool GetParentData01(int nitemId, int nTipoDepartamento, ref string szParentName, ref int nParentId)
        {
            bool bStatus = false;
            int nParentIdHlp = 0;
            IQueryable<ScapDepartment> qryDpto = null;
            ScapDepartment departamento = null;

            //Get the item
            //qryDpto = db.Departments.Where(dpt => dpt.TypeId == nTipoDepartamento && dpt.ParentDepartmentId == nitemId);
            //departamento = qryDpto.FirstOrDefault<ScapDepartment>();
            departamento = db.Departments.Find(nitemId);
            if (departamento != null)
            {
                if (departamento.ParentDepartmentId == null)
                {
                    nParentId = departamento.Id;
                    szParentName = departamento.Name;
                    bStatus = true;
                    return bStatus;
                }
                else
                {
                    nParentIdHlp = Convert.ToInt32(departamento.ParentDepartmentId);
                    bStatus = GetParentData01(nParentIdHlp, departamento.TypeId, ref szParentName, ref nParentId);
                }
            }

            return bStatus;
        }


        //
        // POST: /tabsEmpleado/AddEmployee
        [HttpPost]
        [NoCache]
        public ActionResult AddEmployee(ScapEmployee scapemployee, string departamentId, string departamentId01, string selectDateHlpId, string TipoEmpleado, string StatusEmpleado, string areaId, string areaIdHlp)
        {
            int nEmployeeId = 0;
            int nDepartamentoId = 0;
            int nTipoDepartamento = 0;
            int nTipoEmpleado = 0;
            int nStatusEmpleado = 0;
            int nRole = 0;
            int nPos = -1;
            string szError = "";
            DateTime dStart = DateTime.Now;

            IQueryable<ScapDepartment> qryDepto = null;
            ScapDepartment departamento = null;
            IQueryable<ScapDepartmentType> qryTpDp = null;
            ScapDepartmentType TipoDepartamento = null;
            IQueryable<ScapDepartmentEmployee> qryDptoEmpl = null;
            ScapDepartmentEmployee departamentoempleado = null;
            IQueryable<ScapEmployeeRole> qryRol = null;
            ScapEmployeeRole roles = null;

            if (ModelState.IsValid)
            {
                if (scapemployee.Id == 0)
                {
                    db.Employees.Add(scapemployee);
                    db.SaveChanges();

                    //Manage DepartamentEmployee record
                    nEmployeeId = scapemployee.Id;
                    ManageDepartamentEmployeeData(nEmployeeId, departamentId, departamentId01, selectDateHlpId, TipoEmpleado, StatusEmpleado, areaId, areaIdHlp, ref szError);
                    db.SaveChanges();
                }
                else
                {
                    db.Entry(scapemployee).State = EntityState.Modified;

                    //Validate the root element
                    nPos = departamentId01.IndexOf("\\/");
                    if (nPos != -1)
                    {
                        departamentId01 = string.Empty;
                    }

                    nPos = -1;
                    nPos = areaIdHlp.IndexOf("\\/");
                    if (nPos != -1)
                    {
                        areaIdHlp = string.Empty;
                    }


                    if (!string.IsNullOrEmpty(selectDateHlpId))
                    {
                        dStart = Convert.ToDateTime(selectDateHlpId);
                    }

                    if (!string.IsNullOrEmpty(TipoEmpleado))
                    {
                        nTipoEmpleado = Convert.ToInt32(TipoEmpleado);
                    }

                    if (!string.IsNullOrEmpty(StatusEmpleado))
                    {
                        nStatusEmpleado = Convert.ToInt32(StatusEmpleado);
                    }

                    //Get the default role
                    qryRol = db.EmployeeRoles.Where(rl => rl.Name == "Basico");
                    roles = qryRol.FirstOrDefault<ScapEmployeeRole>();
                    if (roles != null)
                    {
                        nRole = roles.Id;
                    }

                    //Get the search criteria
                    nEmployeeId = scapemployee.Id;

                    qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Departamento");
                    TipoDepartamento = qryTpDp.FirstOrDefault<ScapDepartmentType>();
                    if (TipoDepartamento != null)
                    {
                        nTipoDepartamento = TipoDepartamento.Id;
                    }

                    if (string.IsNullOrEmpty(departamentId01))
                    {
                        qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == departamentId);
                    }
                    else
                    {
                        qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == departamentId01);
                    }
                    departamento = qryDepto.FirstOrDefault<ScapDepartment>();
                    if (departamento != null)
                    {
                        nDepartamentoId = departamento.Id;
                    }

                    if (nEmployeeId != 0)
                    {
                        if (nRole != 0)
                        {
                            if (nDepartamentoId != 0)
                            {
                                //Create/update ScapDepartmentEmployee data 
                                qryDptoEmpl = db.DepartmentEmployees.Where(dptemp => dptemp.RoleId == nRole && dptemp.EmployeeId == nEmployeeId);
                                if (qryDptoEmpl.Count() == 0)
                                {
                                    //Create the record
                                    departamentoempleado = new ScapDepartmentEmployee();
                                    departamentoempleado.EmployeeId = nEmployeeId;
                                    departamentoempleado.RoleId = nRole;
                                    departamentoempleado.DepartmentId = nDepartamentoId;
                                    departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                    departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                    departamentoempleado.StartDate = dStart;
                                    departamentoempleado.IsEnabled = true;
                                    db.DepartmentEmployees.Add(departamentoempleado);

                                }
                                else
                                {
                                    departamentoempleado = qryDptoEmpl.FirstOrDefault<ScapDepartmentEmployee>();
                                    if (departamentoempleado != null)
                                    {
                                        departamentoempleado.EmployeeId = nEmployeeId;
                                        departamentoempleado.RoleId = nRole;
                                        departamentoempleado.DepartmentId = nDepartamentoId;
                                        departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                        departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                        departamentoempleado.StartDate = dStart;
                                        departamentoempleado.IsEnabled = true;
                                        db.Entry(departamentoempleado).State = EntityState.Modified;

                                    }
                                }

                            }
                        }
                    }

                    //Process the Area
                    //Get the default role
                    qryRol = db.EmployeeRoles.Where(rl => rl.Name == "BasicoArea");
                    roles = qryRol.FirstOrDefault<ScapEmployeeRole>();
                    if (roles != null)
                    {
                        nRole = roles.Id;
                    }

                    qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Area");
                    TipoDepartamento = qryTpDp.FirstOrDefault<ScapDepartmentType>();
                    if (TipoDepartamento != null)
                    {
                        nTipoDepartamento = TipoDepartamento.Id;
                    }

                    if (string.IsNullOrEmpty(areaIdHlp))
                    {
                        qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == areaId);
                    }
                    else
                    {
                        qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == areaIdHlp);
                    }
                    departamento = qryDepto.FirstOrDefault<ScapDepartment>();
                    if (departamento != null)
                    {
                        nDepartamentoId = departamento.Id;
                    }

                    if (nEmployeeId != 0)
                    {
                        if (nRole != 0)
                        {
                            if (nDepartamentoId != 0)
                            {
                                //Create/update ScapDepartmentEmployee data 
                                qryDptoEmpl = db.DepartmentEmployees.Where(dptemp => dptemp.RoleId == nRole && dptemp.EmployeeId == nEmployeeId);
                                if (qryDptoEmpl.Count() == 0)
                                {
                                    //Create the record
                                    departamentoempleado = new ScapDepartmentEmployee();
                                    departamentoempleado.EmployeeId = nEmployeeId;
                                    departamentoempleado.RoleId = nRole;
                                    departamentoempleado.DepartmentId = nDepartamentoId;
                                    departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                    departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                    departamentoempleado.StartDate = dStart;
                                    departamentoempleado.IsEnabled = true;
                                    db.DepartmentEmployees.Add(departamentoempleado);

                                }
                                else
                                {
                                    departamentoempleado = qryDptoEmpl.FirstOrDefault<ScapDepartmentEmployee>();
                                    if (departamentoempleado != null)
                                    {
                                        departamentoempleado.EmployeeId = nEmployeeId;
                                        departamentoempleado.RoleId = nRole;
                                        departamentoempleado.DepartmentId = nDepartamentoId;
                                        departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                        departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                        departamentoempleado.StartDate = dStart;
                                        departamentoempleado.IsEnabled = true;
                                        db.Entry(departamentoempleado).State = EntityState.Modified;

                                    }
                                }

                            }
                        }
                    }

                    db.SaveChanges();
                }
                return RedirectToAction("Index", "Employee");
            }
            ViewBag.OriginCityId = new SelectList(db.LocationCities, "Id", "Name", scapemployee.OriginCityId);
            ViewBag.ResidenceCityId = new SelectList(db.LocationCities, "Id", "Name", scapemployee.ResidenceCityId);


            return View(scapemployee);
        }

        private void ManageDepartamentEmployeeData(int nEmployeeId, string departamentId, string departamentId01, string selectDateHlpId, string TipoEmpleado, string StatusEmpleado, string areaId, string areaIdHlp, ref string szError)
        {
            int nDepartamentoId = 0;
            int nTipoDepartamento = 0;
            int nTipoEmpleado = 0;
            int nStatusEmpleado = 0;
            int nRole = 0;
            int nPos = -1;
            DateTime dStart = DateTime.Now;

            IQueryable<ScapDepartment> qryDepto = null;
            ScapDepartment departamento = null;
            IQueryable<ScapDepartmentType> qryTpDp = null;
            ScapDepartmentType TipoDepartamento = null;
            IQueryable<ScapDepartmentEmployee> qryDptoEmpl = null;
            ScapDepartmentEmployee departamentoempleado = null;
            IQueryable<ScapEmployeeRole> qryRol = null;
            ScapEmployeeRole roles = null;

            try
            {
                ////
                //Validate the root element
                nPos = departamentId01.IndexOf("\\/");
                if (nPos != -1)
                {
                    departamentId01 = string.Empty;
                }

                nPos = -1;
                nPos = areaIdHlp.IndexOf("\\/");
                if (nPos != -1)
                {
                    areaIdHlp = string.Empty;
                }


                if (!string.IsNullOrEmpty(selectDateHlpId))
                {
                    dStart = Convert.ToDateTime(selectDateHlpId);
                }

                if (!string.IsNullOrEmpty(TipoEmpleado))
                {
                    nTipoEmpleado = Convert.ToInt32(TipoEmpleado);
                }

                if (!string.IsNullOrEmpty(StatusEmpleado))
                {
                    nStatusEmpleado = Convert.ToInt32(StatusEmpleado);
                }

                //Get the default role
                qryRol = db.EmployeeRoles.Where(rl => rl.Name == "Basico");
                roles = qryRol.FirstOrDefault<ScapEmployeeRole>();
                if (roles != null)
                {
                    nRole = roles.Id;
                }

                //Get the search criteria

                qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Departamento");
                TipoDepartamento = qryTpDp.FirstOrDefault<ScapDepartmentType>();
                if (TipoDepartamento != null)
                {
                    nTipoDepartamento = TipoDepartamento.Id;
                }

                if (string.IsNullOrEmpty(departamentId01))
                {
                    qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == departamentId);
                }
                else
                {
                    qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == departamentId01);
                }
                departamento = qryDepto.FirstOrDefault<ScapDepartment>();
                if (departamento != null)
                {
                    nDepartamentoId = departamento.Id;
                }

                if (nEmployeeId != 0)
                {
                    if (nRole != 0)
                    {
                        if (nDepartamentoId != 0)
                        {
                            //Create/update ScapDepartmentEmployee data 
                            qryDptoEmpl = db.DepartmentEmployees.Where(dptemp => dptemp.RoleId == nRole && dptemp.EmployeeId == nEmployeeId);
                            if (qryDptoEmpl.Count() == 0)
                            {
                                //Create the record
                                departamentoempleado = new ScapDepartmentEmployee();
                                departamentoempleado.EmployeeId = nEmployeeId;
                                departamentoempleado.RoleId = nRole;
                                departamentoempleado.DepartmentId = nDepartamentoId;
                                departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                departamentoempleado.StartDate = dStart;
                                departamentoempleado.IsEnabled = true;
                                db.DepartmentEmployees.Add(departamentoempleado);

                            }
                            else
                            {
                                departamentoempleado = qryDptoEmpl.FirstOrDefault<ScapDepartmentEmployee>();
                                if (departamentoempleado != null)
                                {
                                    departamentoempleado.EmployeeId = nEmployeeId;
                                    departamentoempleado.RoleId = nRole;
                                    departamentoempleado.DepartmentId = nDepartamentoId;
                                    departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                    departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                    departamentoempleado.StartDate = dStart;
                                    departamentoempleado.IsEnabled = true;
                                    db.Entry(departamentoempleado).State = EntityState.Modified;

                                }
                            }

                        }
                    }
                }

                //Process the Area
                //Get the default role
                qryRol = db.EmployeeRoles.Where(rl => rl.Name == "BasicoArea");
                roles = qryRol.FirstOrDefault<ScapEmployeeRole>();
                if (roles != null)
                {
                    nRole = roles.Id;
                }

                qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Area");
                TipoDepartamento = qryTpDp.FirstOrDefault<ScapDepartmentType>();
                if (TipoDepartamento != null)
                {
                    nTipoDepartamento = TipoDepartamento.Id;
                }

                if (string.IsNullOrEmpty(areaIdHlp))
                {
                    qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == areaId);
                }
                else
                {
                    qryDepto = db.Departments.Where(depto => depto.TypeId == nTipoDepartamento && depto.Name == areaIdHlp);
                }
                departamento = qryDepto.FirstOrDefault<ScapDepartment>();
                if (departamento != null)
                {
                    nDepartamentoId = departamento.Id;
                }
                else
                {
                    nDepartamentoId = 0;
                }

                if (nEmployeeId != 0)
                {
                    if (nRole != 0)
                    {
                        if (nDepartamentoId != 0)
                        {
                            //Create/update ScapDepartmentEmployee data 
                            qryDptoEmpl = db.DepartmentEmployees.Where(dptemp => dptemp.RoleId == nRole && dptemp.EmployeeId == nEmployeeId);
                            if (qryDptoEmpl.Count() == 0)
                            {
                                //Create the record
                                departamentoempleado = new ScapDepartmentEmployee();
                                departamentoempleado.EmployeeId = nEmployeeId;
                                departamentoempleado.RoleId = nRole;
                                departamentoempleado.DepartmentId = nDepartamentoId;
                                departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                departamentoempleado.StartDate = dStart;
                                departamentoempleado.IsEnabled = true;
                                db.DepartmentEmployees.Add(departamentoempleado);

                            }
                            else
                            {
                                departamentoempleado = qryDptoEmpl.FirstOrDefault<ScapDepartmentEmployee>();
                                if (departamentoempleado != null)
                                {
                                    departamentoempleado.EmployeeId = nEmployeeId;
                                    departamentoempleado.RoleId = nRole;
                                    departamentoempleado.DepartmentId = nDepartamentoId;
                                    departamentoempleado.EmployeeTypeId = nTipoEmpleado;
                                    departamentoempleado.EmploymentStatusId = nStatusEmpleado;
                                    departamentoempleado.StartDate = dStart;
                                    departamentoempleado.IsEnabled = true;
                                    db.Entry(departamentoempleado).State = EntityState.Modified;

                                }
                            }

                        }
                    }
                }


                ////
            }
            catch (Exception err)
            {
                szError = err.Message;
            }
        }

        //private void ManageDepartamentEmployeeData(string departamentId, string departamentId01, string selectDateHlpId, string TipoEmpleado, string StatusEmpleado, string areaId, string areaIdHlp, ref string szError)
        //{
        //    int nEmployeeId = 0;
        //    int nDepartamentoId = 0;
        //    int nTipoDepartamento = 0;
        //    int nTipoEmpleado = 0;
        //    int nStatusEmpleado = 0;
        //    int nRole = 0;
        //    int nPos = -1;
        //    DateTime dStart = DateTime.Now;

        //    IQueryable<ScapDepartment> qryDepto = null;
        //    ScapDepartment departamento = null;
        //    IQueryable<ScapDepartmentType> qryTpDp = null;
        //    ScapDepartmentType TipoDepartamento = null;
        //    IQueryable<ScapDepartmentEmployee> qryDptoEmpl = null;
        //    ScapDepartmentEmployee departamentoempleado = null;
        //    IQueryable<ScapEmployeeRole> qryRol = null;
        //    ScapEmployeeRole roles = null;

        //}


        // 
        // GET: /tabsEmpleado/
        [NoCache]
        public PartialViewResult Index(int? page)
        {
            bool bHasPreviousPage = false;
            bool bHasNextPage = false;
            int nHas = 0;
            int nPageCount = 1;
            int nPageNumber = 0;
            int pageIndex = 0;
            int pageSize = PageSize;
            //pageSize = 2;

            IQueryable<ScapEmployee> qryEmpl = null;
            ScapEmployee employee = null;

            //Obtiene los empleados
            List<ScapEmployee> employeeList = new List<ScapEmployee>();

            qryEmpl = db.Employees.OrderBy(empl => empl.LastName);
            if (qryEmpl.Count() > 0)
            {
                foreach (var item in qryEmpl)
                {
                    employeeList.Add(item);
                }
            }

            //Set the page
            if (page == null)
            {
                pageIndex = 1;
            }
            else
            {
                pageIndex = Convert.ToInt32(page);
            }

            nHas = employeeList.Count;
            nPageCount = nHas / pageSize;

            var objList = employeeList.ToPagedList(pageIndex, pageSize);
            employeeList = new List<ScapEmployee>();
            foreach (var item in objList)
            {
                employeeList.Add(item);
            }

            //double nMod = nHas & pageSize;
            int nModi = nHas % pageSize;
            if (nModi == 0)
            {
                //nPageCount = 1;
                bHasNextPage = false;
                bHasPreviousPage = false;
            }
            if (nModi < pageSize)
            {
                bHasNextPage = true;
                bHasPreviousPage = true;
                //nPageCount++;

                if (pageIndex == 1)
                {
                    bHasPreviousPage = false;
                }
                if (nPageCount == pageIndex)
                {
                    bHasNextPage = false;
                }

                if (nPageCount == 0)
                {
                    bHasNextPage = false;
                    bHasPreviousPage = false;
                }
            }

            nPageNumber = pageIndex;
            ViewBag.PageCount = nPageCount;
            ViewBag.PageNumber = nPageNumber;
            ViewBag.HasPreviousPage = bHasPreviousPage;
            ViewBag.HasNextPage = bHasNextPage;

            //Set the id of the main div
            ViewBag.MainDiv = "tabsEmpleadodivId";

            //return PartialView(employeeList.ToPagedList(pageIndex, pageSize));
            return PartialView(employeeList);
        }

        // 
        // POST: /tabsEmpleado/
        [NoCache]
        [HttpPost]
        public PartialViewResult Index(int? page, string identificacionid, string nombreid, string tarjetaNoid, string celularid, string departamentosearchid, string nsssearchid)
        {
            bool bHasPreviousPage = false;
            bool bHasNextPage = false;
            int nHas = 0;
            int nPageCount = 1;
            int nPageCountHlp = 1;
            int nPageNumber = 0;
            int pageIndex = 0;
            int pageSize = PageSize;
            //pageSize = 2;

            IQueryable<ScapEmployee> qryEmpl = null;
            ScapEmployee employee = null;

            //Obtiene los empleados
            List<ScapEmployee> employeeList = new List<ScapEmployee>();

            qryEmpl = db.Employees.OrderBy(empl => empl.LastName);

            if (!string.IsNullOrEmpty(identificacionid))
            {
                qryEmpl = db.Employees.Where(empl => empl.Identification.StartsWith(identificacionid)).OrderBy(empl => empl.LastName);
                ViewBag.IdentificacionId = identificacionid;
            }

            if (!string.IsNullOrEmpty(nombreid))
            {
                qryEmpl = db.Employees.Where(empl => empl.LastName.StartsWith(nombreid)).OrderBy(empl => empl.LastName);
                ViewBag.Nombreid = nombreid;
            }

            if (!string.IsNullOrEmpty(celularid))
            {
                qryEmpl = db.Employees.Where(empl => empl.CellPhone.StartsWith(celularid)).OrderBy(empl => empl.LastName);
                ViewBag.Celularid = celularid;
            }

            if (!string.IsNullOrEmpty(nsssearchid))
            {
                qryEmpl = db.Employees.Where(empl => empl.SocialSecurityNumber.StartsWith(nsssearchid)).OrderBy(empl => empl.LastName);
                ViewBag.Nsssearchid = nsssearchid;
            }

            if (qryEmpl.Count() > 0)
            {
                foreach (var item in qryEmpl)
                {
                    employeeList.Add(item);
                }
            }

            //Set the page
            if (page == null)
            {
                pageIndex = 1;
            }
            else
            {
                pageIndex = Convert.ToInt32(page);
            }

            nHas = employeeList.Count;
            nPageCount = nHas / pageSize;

            var objList = employeeList.ToPagedList(pageIndex, pageSize);
            employeeList = new List<ScapEmployee>();
            foreach (var item in objList)
            {
                employeeList.Add(item);
            }

            //double nMod = nHas & pageSize;
            int nModi = nHas % pageSize;
            if (nModi == 0)
            {
                nPageCountHlp = 1;
                bHasNextPage = false;
                bHasPreviousPage = false;
            }
            if (nModi < pageSize)
            {
                bHasNextPage = true;
                bHasPreviousPage = true;
                nPageCountHlp = nPageCount + 1;

                if (pageIndex == 1)
                {
                    bHasPreviousPage = false;
                }
                if (nPageCount == pageIndex)
                {
                    bHasNextPage = false;
                }

                if (nPageCount == 0)
                {
                    bHasNextPage = false;
                    bHasPreviousPage = false;
                }
            }

            nPageNumber = pageIndex;
            ViewBag.PageCount = nPageCount;
            ViewBag.PageNumber = nPageNumber;
            ViewBag.HasPreviousPage = bHasPreviousPage;
            ViewBag.HasNextPage = bHasNextPage;

            //Set the id of the main div
            ViewBag.MainDiv = "tabsEmpleadodivId01";

            //return PartialView(employeeList.ToPagedList(pageIndex, pageSize));
            return PartialView(employeeList);
        }

    }
}
